# jukeeServerWindow.py - Jukee
#
# Copyright (C) 2008 Ruben Medellin <ruben.medellin.c@gmail.com>
#
#    This program is free software; you can redistribute it and/or modify
#    it under the terms of the GNU General Public License as published by
#    the Free Software Foundation; either version 2 of the License, or
#    (at your option) any later version.
#    This program is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.
#    You should have received a copy of the GNU General Public License
#    along with this program; if not, write to the
#    Free Software Foundation, Inc., 59 Temple Place, Suite 330,
#    Boston, MA  02111-1307  USA

"""
In this module is the graphical user interface for the Jukee server.
Is intended to administer basic things of the playlist, as well as to visualize it
and control some features of it.
"""


import pygtk
pygtk.require("2.0")
import gtk
import gtk.glade

import os.path as path
import sys

from jukee.utils.utils import debug, warn, error
from jukee.libs.Observable import Observer
from jukee.server.jukebox import Jukebox

class JukeeServerWindow(Observer):
  """
  Contains the interface for the server program. It is based on a glade file
  and contains the main features for the program
  """

  STATUS_PAUSED  = 'paused'
  STATUS_PLAYING = 'playing'

  def __init__(self, jukee_server):
    
    # Initializes observer
    Observer.__init__(self)

    # Set the jukee server we will use to communicate with, and observe the jukebox object
    self.jukee_server = jukee_server
    self.jukebox = jukee_server.jukebox
    self.observe(self.jukebox)

    # Grab the glade file
    self.gladefile = path.join(path.dirname(__file__), "jukee_server_gui.glade")
    debug("Loading glade file: " + self.gladefile)
    self.wTree = gtk.glade.XML(self.gladefile)

    self.status = JukeeServerWindow.STATUS_PAUSED
    
    # Get the main window
    self.window = self.wTree.get_widget("jukee_server_gui_window")
    
    if not self.window:
      error("Error in glade file. Aborting")
      sys.exit("Glade error")

    # Initialize the signal handlers
    signals = {
      'on_refresh_pipeline_button_clicked': self.refresh_pipeline,
      'on_skip_button_clicked': self.skip_song,
      'on_play_pause_button_clicked': self.play_pause
    }
    self.wTree.signal_autoconnect(signals)
    self.window.connect("destroy", gtk.main_quit)

    # Add client view
    self.client_list_store = gtk.ListStore(
      str,      # Name column
      str       # Hostname column
    )

    client_list_view = self.wTree.get_widget("client_list_view")
    client_list_view.set_model(self.client_list_store)

    ## OPTIMIZE: Refactor this routines into a method
    col_view = gtk.TreeViewColumn("Name")
    client_list_view.append_column(col_view)
    renderer = gtk.CellRendererText()
    col_view.pack_start(renderer, True)
    col_view.set_attributes(renderer, text = 0)
    
    col_view = gtk.TreeViewColumn("Hostname")
    client_list_view.append_column(col_view)
    renderer = gtk.CellRendererText()
    col_view.pack_start(renderer, True)
    col_view.set_attributes(renderer, text = 1)
  
    # Add playlist view
    self.playlist_list_store = gtk.ListStore(str)
    playlist_list_view = self.wTree.get_widget("playlist_list_view")
    playlist_list_view.set_model(self.playlist_list_store)

    col_view = gtk.TreeViewColumn("Song")
    playlist_list_view.append_column(col_view)
    renderer = gtk.CellRendererText()
    col_view.pack_start(renderer, True)
    col_view.set_attributes(renderer, text = 0)


  def refresh_pipeline(self, widget, data = None):
    """Calls refresh on the player object"""
    self.jukebox.player.refresh()
    debug("Pipeline refreshed")

  def play_pause(self, widget, data = None):
    """Pauses and resumes playback"""

    button = self.wTree.get_widget("play_pause_button")
    if self.status == JukeeServerWindow.STATUS_PAUSED:
      debug("Paused to playing")
      self.status = JukeeServerWindow.STATUS_PLAYING
      self.jukebox.player.resume()
      button.set_label("gtk-media-pause")
    elif self.status == JukeeServerWindow.STATUS_PLAYING:
      debug("Playing to paused")
      self.status = JukeeServerWindow.STATUS_PAUSED
      self.jukebox.player.pause()
      button.set_label("gtk-media-play")
    button.realize()

  def skip_song(self, widget, data = None):
    # TODO: Implement
    debug("Skipping song")

  def processEvent(self, notifier, event_name, *arguments):
    debug("Received event on GUI")
    if notifier == self.jukebox:
      if event_name == Jukebox.CLIENT_JOINED:
        self.client_added(arguments[0])
      elif event_name == Jukebox.NEW_SONG_PLAYING:
        self.new_song_playing(arguments[0])

  def client_added(self, client):
    debug("Gui: Client " + str(client) + " joined")
    self.client_list_store.append([client['name'], client['hostname']])

  def new_song_playing(self, song):
    debug("Gui: New song playing: " + str(song))
    self.playlist_list_store.append([song])
    if self.status == JukeeServerWindow.STATUS_PAUSED:
      self.status = JukeeServerWindow.STATUS_PLAYING
      self.jukebox.player.resume()

  def main(self):
    self.window.show()
    gtk.main()
